/**
 * Check 1 string is numberic
 **/
function isNumeric(input)
{
    return (input - 0) == input && (''+input).replace(/^\s+|\s+$/g, "").length > 0;
}

// form so sau khi lost focus
function formatNumber(obj)
{
    obj = $(obj);
    var fix = 0;

    if( obj.attr('fix') )
        fix = parseInt( obj.attr('fix') );

    obj.blur(function(){
        var v = obj.val( );

        if( v.length == 0 ) return false;

        if( v.indexOf( ',' ) > 0 ) return;

        v = v.replaceAll( '.', '').replaceAll( ',', '.');

        obj.val( formatMoney( parseFloat( v  ), fix ) );
    });
}

function formatMoney(num, fix) {

    if( num == 0 ) return num;

    var p = num.toFixed(fix);

    if( p < 1000 )  return (p + "").replace(".", ",");

    return  p.split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "." : "") + acc;
    }, "");
}

/**
 * check als
 */
function checkAlias() {
	$('.alias').keyup(function(){
        if (this.value.match(/[^a-zA-Z0-9_-]/g)) {
            this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '');
        }
    });
}

function formatDollar(num) {

    var p = num.toFixed(2).split(".");

    return  p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "");
}


/*
*  ajax_post_update : Update data to server with post method
*  @param
*  url: Url to post data
*  data: Data - use  serialize : var data = $('form_id').serialize()
*  succ_message: String - message content show after post success
*  update: Container update response data after success
*          - sample: #contain, jQuery('#contain')
*
*  use : ajax_post_update('/locations/update', 'id=10&text=Michael', 'updated success', jQuery('#update'))
*/

function postAjax(url, data, callback, json, loading){

	if(!json) json = 'json';

	if(!loading) loading = false;

    return $.ajax({
        url: url,
        data: data,
        dataType: json,
        async: true,
        type: 'POST',

		beforeSend: function(request) {
			if(loading) showLoading();
        },
        complete: function(){
        	hideLoading();
        },
        success: function(msg){
            if (typeof(callback) === "function") {
                callback(msg);
            }
        },
        statusCode: {
            401: function(){
            }
        },
        error: function(xhr, status, err){
        	if (typeof(callback) === "function") {
                callback({code:'danger', err:err, msg:'Error ajax'});
            }
        }
    });
}


/**
* Load ajax request: this function use to load content from server
*
* params:
*   - url: url request content
*   - async : true, false
*/

function getAjax(url, async, callback, datatype, loading )
{
	if(typeof(datatype) == 'undefined') datatype = 'json';

    jQuery.ajax(
    {   url: url,
        type: 'GET',
        dataType: datatype,
        cache:true,
        success: function(msg)
        {
            var $msg = jQuery(msg);

            if( typeof( callback ) === "function" )
            {
                callback(msg);
            }
            else
            	return msg;
        },

        error: function(xhr, status, err) {
            if (xhr.status == 401){}
                //window.location.href = '/login';
            return xhr;
        },

        beforeSend:function()
        {
            if( loading ) {}
        },
        async:async,

    });
}


/**
*  clear_form_elements: Clear data of controls of form
*
*  params: from id - #form1
*/
  function clear_form_elements($html) {

      $html.find(':input').each(function () {
          switch (this.type) {
              case 'password':
              case 'select-multiple':
              case 'select-one':
              case 'text':
              case 'textarea':
                  $(this).val('').attr('value', '');
                  break;
              case 'checkbox':
              case 'radio':
                  this.checked = false;
          }
      });

 }

 function showLoading() {
	var loading = '<div class="loading"><div></div><img src="'+ webroot +'/img/loading1.gif" /></div>';
	$('body').append(loading);
}

function hideLoading() {
	$('.loading').remove();
}

 /**
 * Select all checkbox
 *
 * params:
 *   flag: true-> check all; false -> uncheck all
 *   parent: element contains all check box
 */
 function select_all(flag, parent)
 {
     if( parent = null )
     {
         parent = jQuery(document);
     }
     if( flag )
     {
         jQuery(':checkbox', parent).attr('checked', 'checked' );
     }
     else
     {
         jQuery(':checkbox', parent).removeAttr('checked' );
     }
 }


/**
 * Replaces all instances form @param:'strTarget' to @param:'strSubString' of the given substring.
 *
 * @param: strTarget is string or array()
 * @param: strSubString
 *
 **/
String.prototype.replaceAll = function( strTarget,  strSubString ){
	var strText = this;

	if($.isArray(strTarget)) {
		strTarget.forEach(function(val, i){
			strText = strText.replaceAll(val, strSubString);
		});
		return( strText );
	} else {
	    var intIndexOfMatch = strText.indexOf( strTarget );

	    // Keep looping while an instance of the target string
	    // still exists in the string.
	    while (intIndexOfMatch != -1){
		    // Relace out the current instance.
		    strText = strText.replace( strTarget, strSubString )

		    // Get the index of any next matching substring.
		    intIndexOfMatch = strText.indexOf( strTarget );
	    }

	    // Return the updated string with ALL the target strings
	    // replaced out with the new substring.
	    return( strText );
	}
}
